<template>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="workOrderNumber" label="工单号" width="120" />
        <el-table-column prop="workSection" label="工段" width="120" />
        <el-table-column prop="workOrderType" label="工单类型" width="120" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="formulaVersion" label="配方版本" width="120" />
        <el-table-column prop="processVersion" label="工艺版本" width="120" />
        <el-table-column prop="unit" label="单位" width="120" />
        <el-table-column prop="workshop" label="车间" width="120" />
        <el-table-column prop="productionLine" label="产线" width="120" />
        <el-table-column prop="documentSource" label="单据来源" width="120" />
        <el-table-column prop="productName" label="产品名称" width="120" />
        <el-table-column prop="processRoute" label="工艺路线" width="120" />
        <el-table-column prop="plannedQuantity" label="计划量" width="120" />
        <el-table-column prop="plannedStartTime" label="计划开始时间" width="120" />
        <el-table-column prop="plannedEndTime" label="计划结束时间" width="120" />
        <el-table-column fixed="right" label="Operations" min-width="180">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleClick">
                    Detail
                </el-button>
                <el-button link type="primary" size="small"
                    @click="dialogFormVisible = true; FanTian(scope.row)">修改</el-button>
                <el-button link type="danger" size="small" @click="deleteTicket(scope.row.ticketId)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
        <el-form :model="formData">
            <div class="form-column">
                <el-form-item label="工单号：">
                    <el-input v-model="formData.workOrderNumber" readonly />
                </el-form-item>
                <el-form-item label="工段：">
                    <el-select v-model="formData.workSection" placeholder="请选择工段">
                        <el-option v-for="item in workSections" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="工单类型：">
                    <el-select v-model="formData.workOrderType" placeholder="请选择工单类型">
                        <el-option label="正常工单" value="正常工单"></el-option>
                        <el-option label="加急工单" value="加急工单"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="产品编码：">
                    <el-input v-model="formData.productCode" readonly>
                    </el-input>
                </el-form-item>
                <el-form-item label="配方版本：">
                    <el-input v-model="formData.formulaVersion">
                    </el-input>
                </el-form-item>
                <el-form-item label="工艺版本：">
                    <el-input v-model="formData.processVersion">
                    </el-input>
                </el-form-item>
                <el-form-item label="单位：">
                    <el-input v-model="formData.unit" readonly />
                </el-form-item>
            </div>
            <div class="form-column">
                <el-form-item label="车间：">
                    <el-select v-model="formData.workshop" placeholder="请选择车间">
                        <el-option v-for="item in workshops" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="产线：">
                    <el-select v-model="formData.productionLine" placeholder="请选择产线">
                        <el-option v-for="item in productionLines" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="单据来源：">
                    <el-select v-model="formData.documentSource" placeholder="请选择单据来源">
                        <el-option v-for="item in documentSources" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="产品名称：">
                    <el-input v-model="formData.productName" readonly @click="showDialog" />
                </el-form-item>
                <el-form-item label="工艺路线：">
                    <el-input v-model="formData.processRoute" />
                </el-form-item>
                <el-form-item label="计划量：">
                    <el-input v-model="formData.plannedQuantity" />
                </el-form-item>
                <el-form-item label="计划开始时间：">
                    <el-date-picker v-model="formData.plannedStartTime" type="datetime" placeholder="选择日期时间"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
                <el-form-item label="计划结束时间：">
                    <el-date-picker v-model="formData.plannedEndTime" type="datetime" placeholder="选择日期时间"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                </el-form-item>
            </div>
        </el-form>
        <template #footer="scope">
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">Cancel</el-button>
                <el-button type="primary" @click="dialogFormVisible = false; Update(formData.value)">
                    修改
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 产品名称 -->
    <el-dialog v-model="dialogTableVisible" title="产品信息" width="800" draggable>
        <el-table :data="productsModellist" @row-click="selectProduct">
            <el-table-column property="productsName" label="产品名称" width="150" />
            <el-table-column property="productsNumber" label="编号" width="200" />
            <el-table-column property="productsType" label="规格" />
            <el-table-column property="productsUnit" label="单位" />
            <el-table-column property="price" label="价格" />
            <el-table-column property="remark" label="数量" />
        </el-table>
    </el-dialog>
    <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize" :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
const handleClick = () => {
    console.log('click')
}

// 显示对话框的方法
const showDialog = () => {
    dialogTableVisible.value = true
}

const dialogTableVisible = ref(false)

const dialogFormVisible = ref(false);

// 生成唯一工单号的函数
const generateWorkOrderNumber = () => {
    const date = new Date()
    const year = date.getFullYear().toString().slice(2) // 获取年份后两位
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    const second = date.getSeconds().toString().padStart(2, '0')
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')

    return `WO${year}${month}${day}${hour}${minute}${second}${random}`
}

const Update = (data: any) => {
    axios.post('https://localhost:7229/api/Ticket/UpdateTicket', data)
        .then((response) => {
            console.log(response.data)
            // 更新表格数据
            getTicket()
        })
        .catch((error) => {
            console.error('修改失败:', error)
        })
}

const tableData = ref([{
    ticketId: 0,
    workOrderNumber: generateWorkOrderNumber(),
    workSection: "",
    workOrderType: "",
    productCode: "",
    formulaVersion: "",
    processVersion: "",
    unit: "",
    workshop: "",
    productionLine: "",
    documentSource: "",
    productName: "",
    processRoute: "",
    plannedQuantity: "",
    plannedStartTime: "",
    plannedEndTime: ""
}])

const formData = ref({
    ticketId: 0,
    workOrderNumber: generateWorkOrderNumber(),
    workSection: "",
    workOrderType: "",
    productCode: "",
    formulaVersion: "",
    processVersion: "",
    unit: "",
    workshop: "",
    productionLine: "",
    documentSource: "",
    productName: "",
    processRoute: "",
    plannedQuantity: "",
    plannedStartTime: "",
    plannedEndTime: ""
})
const productsModel = () => {
    axios.get('http://8.154.44.176:8000/c-read/api/Products/GetProducts').then((response) => {
        productsModellist.value = response.data.data
        console.log("产品表", productsModellist.value)
    })
}

const productsModellist = ref([{
    productsId: 0,
    productsName: "",
    productsNumber: "",
    productsType: "",
    productsUnit: "",
    productsNum: "",
    price: 0,
    remark: "",
    del: true
}])

// 选择产品的方法
const selectProduct = (row) => {
    const selectedId = row.productsId
    console.log('选中的 productsId:', selectedId)
    formData.value.productName = row.productsName
    formData.value.productCode = row.productsNumber
    formData.value.unit = row.productsUnit
    dialogTableVisible.value = false
}

// 模拟车间数据
const workshops = ref([
    { value: '包装车间1', label: '包装车间1' },
    { value: '包装车间2', label: '包装车间2' }
])

// 模拟工段数据
const workSections = ref([
    { value: '包装工段1', label: '包装工段1' },
    { value: '包装工段2', label: '包装工段2' }
])

// 模拟产线数据
const productionLines = ref([
    { value: '包装产线1', label: '包装产线1' },
    { value: '包装产线2', label: '包装产线2' }
])

// 模拟单据来源数据
const documentSources = ref([
    { value: '系统自动生成', label: '系统自动生成' },
    { value: '手动录入', label: '手动录入' },
    { value: '外部导入', label: '外部导入' }
])

const FanTian = (row) => {
    Object.assign(formData.value, row);
    if (!formData.value.workOrderNumber) {
        formData.value.workOrderNumber = generateWorkOrderNumber();
    }
}

onMounted(() => {
    getTicket();
    productsModel();
})

const page = ref({
    pageIndex: 1,
    pageSize: 10,
    totalCount: 0,
    totalPage: 0
})

const getTicket = () => {
    axios.get('https://localhost:7238/api/Ticker/Handle', {
        params: {
            pageIndex: page.value.pageIndex,
            pageSize: page.value.pageSize
        }
    }).then((res) => {
        tableData.value = res.data.data
        page.value.totalCount = res.data.totalCount
        page.value.totalPage = res.data.totalPage
    })
}

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    page.value.pageSize = val
    getTicket()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    page.value.pageIndex = val
    getTicket()
}

const deleteTicket = (ticketId: number) => {
    if (confirm('确定要删除该工单吗？')) {
        axios.post(`https://localhost:7229/api/Ticket/DeleteTicket`, {
            ticketId: ticketId
        })
            .then(() => {
                console.log('删除成功')
                getTicket()
            })
            .catch((error) => {
                console.error('删除失败:', error)
            })
    }
}

</script>

<style scoped>
/* 样式部分可根据实际需求调整 */
</style>